package com.todo.controller;

import java.io.IOException;
import java.util.List;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.todo.model.Task;
import com.todo.service.ITaskService;

@Controller
@RequestMapping(value = "/task")
public final class TaskController {
    private static final Logger logger = LoggerFactory.getLogger(TaskController.class);
    
    @Autowired
    ITaskService taskService;

    @RequestMapping(value = "/list.json", method = RequestMethod.GET)
    @ResponseBody
    public List<Task> taskList() {
        return taskService.listTask();
    }
    
    @RequestMapping(value = "/remove.json", method = RequestMethod.POST)
    @ResponseBody
    public String removeTask(@RequestParam int recordId) {
        logger.info("removeTask!");
        
        taskService.removeTask(recordId);
        
        // TODO task#8 task I think it's not exactly 
        return "success";
    }
    
    @RequestMapping(value = "/create.json", method = RequestMethod.POST)
    @ResponseBody
    public int createTask(@RequestParam String record) throws JsonParseException, JsonMappingException, IOException {
        logger.info("createTask!");
        
        ObjectMapper mapper = new ObjectMapper();
        Task task = mapper.readValue(record,Task.class);
        
        taskService.addTask(task);
        
        // TODO task#8 task I think it's not exactly 
        return task.getId();
    }
    
    @RequestMapping(value = "/update.json", method = RequestMethod.POST)
    @ResponseBody
    public Task updateTask(@RequestParam String record) throws JsonParseException, JsonMappingException, IOException {
        logger.info("updateTask!");
        
        ObjectMapper mapper = new ObjectMapper();
        Task task = mapper.readValue(record,Task.class);
        
        // TODO task#8 task I think it's not exactly 
        return task;
    }
}
